<template>
	<a-form
		:model="formState"
		name="basic"
		:label-col="{ span: 8 }"
		:wrapper-col="{ span: 16 }"
		autocomplete="off"
		@finish="onFinish"
		@finishFailed="onFinishFailed"
	>
		<a-form-item
			label="Username"
			name="userAccount"
			:rules="[
				{
					required: true,
					message: 'Please input your username!',
				},
			]"
		>
			<a-input v-model:value="formState.userAccount" />
		</a-form-item>

		<a-form-item
			label="Password"
			name="userPassword"
			:rules="[
				{
					required: true,
					message: 'Please input your password!',
				},
			]"
		>
			<a-input-password
				v-model:value="formState.userPassword"
			/>
		</a-form-item>

		<a-form-item
			name="remember"
			:wrapper-col="{ offset: 8, span: 16 }"
		>
			<a-checkbox v-model:checked="formState.remember"
				>Remember me
			</a-checkbox>
		</a-form-item>

		<a-form-item :wrapper-col="{ offset: 8, span: 16 }">
			<a-button type="primary" html-type="submit"
				>Submit
			</a-button>
		</a-form-item>
	</a-form>
</template>
<script setup lang="ts">
import { onBeforeMount, reactive } from 'vue';
import api from '@/api';
import { useRouter } from 'vue-router';
import { userLoginUserStore } from '@/stores/loginUser';
import { ApplicationResponseStatusCodeEnum } from '@/enums/ApplicationResponseStatusCodeEnum';
import { message } from 'ant-design-vue';

interface FormState {
	userAccount: string;
	userPassword: string;
	remember: boolean;
}
const router = useRouter();
const redirectFrom = router.currentRoute.value.redirectedFrom?.path || '/';
const userLoginStore = userLoginUserStore();
const formState = reactive<FormState>({
	userAccount: '',
	userPassword: '',
	remember: true,
});
const onFinish = (values: any) => {
	console.log('Success:', values);
	const loginPromise = api.userController.userLogin(values);
	message.loading('登录中...', 2.5);
	loginPromise
		.then(response => {
			message.destroy();
			if (
				ApplicationResponseStatusCodeEnum.SUCCESS ===
				response.data.code
			) {
				message.success('登录成功 正在跳转', 2.5);
				userLoginStore.setLoginUser(response.data.data);
				setTimeout(() => {
					router.replace(redirectFrom);
				}, 3000);
			} else {
				message.error(
					`登录失败: ${response.data.message}`,
				);
			}
		})
		.catch(error => {
			message.error(`登录失败: ${error.message}`);
		});
};

const onFinishFailed = (errorInfo: any) => {
	console.log('Failed:', errorInfo);
};

onBeforeMount(() => {
	if (userLoginStore.isLogin) {
		router.push(redirectFrom);
	}
});


</script>

<style scoped></style>
